<?php
//include_once("../../config/config.php");
include_once("Transform.php");
class GoogleApi{
	private $transform;
	public function GoogleApi(){
		$this->transform = new Transform();
	}
	public function Get($key,$langs=array("en"=>"","ja"=>"","zh-CN"=>"","zh-TW"=>"")){
		try {
			if(!empty($key)){
				$key=strtolower($key);
				$inputlang = NULL;
				/*
				$checklang_url = "http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=$key";
				$checklang_body = file_get_contents($checklang_url,FILE_USE_INCLUDE_PATH);
				$checklang = $this->transform->JsonToArray($checklang_body);
				$inputlang = $checklang["responseData"]["language"];
				print_r($inputlang);
				*/
				if(empty($inputlang)){
					$inputlang = LANG;
					switch($inputlang){
						case "cn":
							$inputlang="zh-CN";
							break;
						case "tw":
							$inputlang="zh-TW";
							break;
					}
					$inputlang = empty($inputlang)?"en":$inputlang;
				}
				$transto = NULL;
				if(is_array($langs)){
					foreach($langs as $lang=>$text){
						$transto .= "&langpair=$inputlang|$lang";
					}
				}
				if(!is_null($transto)){
					$url = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=$key$transto";
					
					$curl = new curl($url);
					$body = $curl->execute();
					
					//$body = file_get_contents($url,FILE_USE_INCLUDE_PATH);
					$trantext = $this->transform->JsonToArray($body);
					$result = $this->GetValue($trantext,"translatedText");
					if(is_array($langs)){
						$i = 0;
						foreach($langs as $resultkey =>$resultval){
							$langs[$resultkey] = checknull($i, $result);
							//$langs[$resultkey] = $result[$i];
							$i++;
						}
					}
				}
			}
			return $langs;
    } catch (Exception $e) {}
	}/**
	 * Get the value array in $input where $key == $searchkey or {$searchkey=>$childkeys[0]=>$childkeys[1]......$childkeys[n]}'s value
	 * @param array $input
	 * @param array $searchkey
	 * @param array $childkeys
	 */
	private function GetValue($input,$searchkey){
		$result = array();
		if(is_array($input)&&!empty($searchkey)){
			if (array_key_exists($searchkey,$input)){
				array_push($result,checknull($searchkey, $input));
			}else{
				foreach($input as $key=>$val){
					$result = array_merge($result,$this->GetValue($val,$searchkey));
				}
			}
		}
		//print_r($result);
		//echo $result."\n";
		return $result;
	}
}
	/*
	$test= new GoogleApi();
	print_r($test->Get("test"));
	*/